// 获取token并判断用户是否登录 token是否过期
const jwt = require('jsonwebtoken');

// is_admin 0普通用户 1管理员 2超级管理员
const isSuper = (req, res, next) => {
    const authorization = req.headers['authorization'];
    if (!authorization) {
        return res.json({
            code: 403,
            message: 'token不能为空',
            success: false
        });
    }
    const token = authorization.split(' ')[1];
    if (!token) {
        return res.json({
            code: 403,
            message: 'token不能为空',
            success: false
        });
    }
    jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
        if (err && err.name === 'TokenExpiredError') {
            return res.json({
                code: 403,
                message: 'token过期',
                success: false
            });
        } else if (err && err.name === 'JsonWebTokenError') {
            return res.json({
                code: 403,
                message: '无效的token',
                success: false
            });
        }
        const isSuper = user.is_admin;
        if (isSuper != 2) {
            return res.json({
                code: 403,
                message: '你不是超级管理员',
                success: false
            });
        }
        req.user_id = user.user_id;
        req.username = user.username;
        req.is_admin = user.is_admin;
        next();
    });
}

module.exports = isSuper;
